

namespace SharpSoft.Data.DAOS
{
    using SharpSoft.Data.GSQL;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    public abstract class DAO : IDisposable
    {
        public DAO(Database p_db, int p_userid = -1)
        {
            this.db = p_db;
            this.userid = p_userid;
        }

        protected Database db;
        private SQLBuilder _nsb;
        /// <summary>
        /// 获取当前数据库关联的<see cref="SQLBuilder"/>对象
        /// </summary>
        protected SQLBuilder nsb
        {
            get
            {
                if (_nsb == null)
                {
                    _nsb = db?.CreateNativeSQLBuilder();
                }
                return _nsb;
            }
        }
        protected int userid;

        public Database Database
        {
            get { return db; }
        }

        protected Stream getResFile(string name)
        {
            Type type = this.GetType();
            var _namespace = type.Namespace;
            System.Reflection.Assembly _assembly = type.Assembly;

            var resourceName = _namespace + "." + name;
            Stream stream = _assembly.GetManifestResourceStream(resourceName);
            return stream;
        }


        /// <summary>
        /// 返回用于创建数据结构的脚本
        /// </summary>
        /// <returns></returns>
        protected virtual void InitSchemaByScriptFile(string schemaFile)
        {

            var stream1 = getResFile(schemaFile);
            if (stream1 == null)
            {
                throw new Exception($"[{schemaFile}]数据结构资源文件不存在，请检查是否存在此文件且已设置文件生成操作为【嵌入的资源】。");
            }
            using (StreamReader sr = new StreamReader(stream1, Encoding.UTF8))
            {
                try
                {
                    string gsql = sr.ReadToEnd();
                    db.ExecuteNonQuery(new GSQLCommandScript(gsql));
                }
                catch (Exception ex)
                {

                    throw new Exception($"{schemaFile} --> {ex.Message}");
                }

            }
        }

        /// <summary>
        /// 在派生类中重写，提供架构文件的名称。
        /// </summary>
        protected abstract string InitScriptFileName { get; }

        /// <summary>
        /// 初始化数据结构，默认使用提供的SchemaFileName指定数据库结构脚本文件
        /// </summary>
        public virtual void InitSchema()
        {
            this.InitSchemaByScriptFile(this.InitScriptFileName);
        }
        /// <summary>
        /// 调用指定DAO类型的初始化脚本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="database"></param>
        public static void InitSchema<T>(Database database)where T:DAO
        {
            T dao = (T)Activator.CreateInstance(typeof(T), database, -1);
            dao.InitSchema();
        }


        public void Dispose()
        {

        }
    }
}
